import { sys } from 'cc';

interface LianLianKan_GameStorageData {
    mode_1:
    {
        level: number,
        item_提示_number: number;
        item_打乱_number: number;
    }
}

export class LianLianKan_GameStorage {
    static data: LianLianKan_GameStorageData = null;
    static defaultValue: LianLianKan_GameStorageData = null;
    static initData() {
        LianLianKan_GameStorage.InitDefaultData();

        let dataStr = sys.localStorage.getItem(`LianLianKan_GameStorage`);
        if (!dataStr || dataStr === "") {
            LianLianKan_GameStorage.clearData();
        } else {
            LianLianKan_GameStorage.data = JSON.parse(dataStr);
            LianLianKan_GameStorage.saveData();
        }

        LianLianKan_GameStorage.SetEveryData();
    }
    //    // 初始化默认值
    static InitDefaultData() {
        LianLianKan_GameStorage.defaultValue = {
            mode_1: {
                level: 1,
                item_提示_number: 10,
                item_打乱_number: 10,
            },
        };
    }
    static SetEveryData() {
        // 递归检查并更新所有属性
        LianLianKan_GameStorage.mergeDataRecursively(LianLianKan_GameStorage.data, LianLianKan_GameStorage.defaultValue);
        LianLianKan_GameStorage.saveData();
    }
    //    // 递归合并数据，确保所有属性都存在
    static mergeDataRecursively(target: any, source: any) {
        for (let key in source) {
            if (source.hasOwnProperty(key)) {
                // 如果目标对象没有这个属性，直接赋值
                if (!target.hasOwnProperty(key)) {
                    target[key] = source[key];
                }
                // 如果目标对象有这个属性，且源对象的值是对象类型，则递归检查
                else if (typeof source[key] === 'object' && source[key] !== null && !Array.isArray(source[key])) {
                    if (typeof target[key] === 'object' && target[key] !== null && !Array.isArray(target[key])) {
                        LianLianKan_GameStorage.mergeDataRecursively(target[key], source[key]);
                    } else {
                        // 如果目标不是对象类型，用默认值替换
                        target[key] = source[key];
                    }
                }
                // 对于数组类型，如果目标没有这个属性，则使用默认值
                else if (Array.isArray(source[key]) && !target.hasOwnProperty(key)) {
                    target[key] = source[key];
                }
            }
        }
    }
    static clearData() {
        LianLianKan_GameStorage.data = { ...LianLianKan_GameStorage.defaultValue };
    }
    static saveData() {
        let dataStr = JSON.stringify(LianLianKan_GameStorage.data);
        sys.localStorage.setItem(`LianLianKan_GameStorage`, dataStr);
    }
}